CSS 접근 및 수정
✒️ 2025-05-23 17:07 내용 수정
- 객체를 먼저 document나 function을 통해 가져와서 변수에 저장한 후, 객체에 있는 style property의 속성값을 변경한다.
- Javascript에서 css style을 변경할 때 Attribute 이름을 Camel 표기법으로 작성해야 한다.
// style property의 특정 css attribute으로 접근
selector.style.fontSize = '28px';
selector.style.backgroundColor = 'yellow';
// 아래처럼 접근할 수도 있다.
selector.style = "color:pink;"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p id="p1">CSS 변경하기</p>
<script>
let target = document.getElementById('p1');
target.style.background = 'lightblue';
target.style.color = 'red';
target.style.font = 'bold 30px';
target.style.border = '2px solid black';
target.setAttribute('marginLeft', '15px');
</script>
</body>
</html>
- 한 번에 여러 속성을 변경할 수 있다.
target.style.cssText = 'color:orange; font-size:15px;';